/**
 * STM32 Intermediate value模型评估固件
 * 
 * 功能：Execute指定Algorithm的指定Intermediate valueCalculate，用于评估CPUUse率相关性
 * Configuration：Throughintermediate_config.h动态ConfigurationAlgorithmAnd模型
 */

#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include "intermediate_models.h"
#include "intermediate_config.h"

// Semihosting exit
void semihosting_exit(int code);

// 延时Function
void delay_cycles(volatile uint32_t count) {
    while(count--);
}

// Output十六进制Data
void print_hex(const char* label, const uint8_t* data, uint32_t len) {
    printf("%s", label);
    for (uint32_t i = 0; i < len; i++) {
        printf("%02x", data[i]);
    }
    printf("\n");
}

int main(void) {
    printf("========================================\n");
    printf("  STM32 Intermediate Value Evaluation\n");
    printf("========================================\n\n");
    
    // DisplayConfigurationInformation
    printf("Configuration:\n");
    printf("  Algorithm: %s\n", ALGORITHM_NAME);
    printf("  Model: %s\n", MODEL_NAME);
    printf("  Traces: %d\n", NUM_TRACES);
    printf("  Trace Delay: %d us\n", TRACE_DELAY_US);
    printf("\n");
    
    // DisplayTestKey
    printf("Test Key: ");
    print_hex("", test_key, KEY_SIZE);
    printf("\n");
    
    // Initialize模型
    printf("Initializing intermediate value model...\n");
    intermediate_model_init(test_key);
    printf("Model initialized\n\n");
    
    printf("========================================\n");
    printf("  Starting Batch Evaluation\n");
    printf("========================================\n\n");
    
    // 批ProcessLoop
    for (int i = 0; i < NUM_TRACES; i++) {
        // 获取InputData
        const uint8_t* input = &test_inputs[i * INPUT_SIZE];
        
        // OutputInputData
        print_hex("INPUT:", input, INPUT_SIZE);
        fflush(stdout);
        
        // OutputTraceStart标记
        printf("TRACE_START:%d\n", i);
        fflush(stdout);
        
        // TRACE_START后延时 - 给Python采集器准备时间并扩展Sampling窗口
        delay_cycles(TRACE_DELAY_US * 100);
        
        // ExecuteIntermediate valueCalculate（这Yes被Monitor的关键操作）
        uint32_t intermediate_value = compute_intermediate_value(input);
        
        // OutputTraceEnd标记
        printf("TRACE_END:%d\n", i);
        fflush(stdout);
        
        // OutputIntermediate valueResult
        printf("INTERMEDIATE:%08x\n", intermediate_value);
        fflush(stdout);
        
        // 进度Display
        if ((i + 1) % 10 == 0) {
            printf("\nProgress: %d/%d (%.1f%%)\n\n",
                   i + 1, NUM_TRACES, 100.0 * (i + 1) / NUM_TRACES);
            fflush(stdout);
        }
    }
    
    printf("\n========================================\n");
    printf("  Batch Evaluation Complete\n");
    printf("========================================\n");
    printf("Total traces: %d\n", NUM_TRACES);
    printf("BATCH_COMPLETE\n");
    fflush(stdout);
    
    // ExitQEMU
    semihosting_exit(0);
    
    return 0;
}
